package eScrum;
import org.apache.wicket.authroles.authentication.AuthenticatedWebSession;
import org.apache.wicket.authroles.authorization.strategies.role.Roles;
import org.apache.wicket.injection.Injector;
import org.apache.wicket.request.Request;
import org.apache.wicket.spring.injection.annot.SpringBean;

import eScrum.entities.User;
import eScrum.services.UserService;
import eScrum.utils.EncryptionUtil;

public class UserSession extends AuthenticatedWebSession {

	private static final long serialVersionUID = 7168455630569871102L;

	private User user;

	@SpringBean
	private UserService userService;

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public UserSession(Request request) {
		super(request);

		Injector.get().inject(this);
	}

	public boolean alreadySignedIn() {
		if (user != null)
			return true;
		return false;
	}

	@Override
	public final boolean authenticate(final String username,
			final String password) {
		if (user == null) {
			user = userService.findUserByUserName(username);
			if (user != null)
				if (user.getPassword().equals(EncryptionUtil.crypt(password))) {
					user.setRoles(user.getRole().toString());
					return true;
				}

		}
		return false;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	@Override
	public Roles getRoles() {
		return this.user.getRoles();
	}

}
